# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: 廖择贵
# createTime: 2021-04-06 22:22:00
# action:连接数据库

import pymysql
from config.setting import config
from pymysql.cursors import DictCursor


class DBHandle(object):

    def __init__(self):
        # 初始化-建立连接
        self.conn = pymysql.connect(host=config.db_host,
                                    port=config.db_port,
                                    user=config.db_user,
                                    password=config.db_password,
                                    charset='utf8',
                                    database=config.db_name,
                                    cursorclass=DictCursor  # 以字典的方式返回数据结果
                                    )
        # 建立游标
        self.cursor = self.conn.cursor()

    def query_sql(self, sql, args=None, one=True):
        # 执行sql语句%s 占位符
        self.cursor.execute(sql, args=args)
        # 获取结果
        if one:
            result = self.cursor.fetchone()
        else:
            result = self.cursor.fetchall()
        return result

    def insert_sql(self, sql, args=None):
        self.cursor.execute(sql, args=args)

    def close_db(self):
        # 关闭游标和连接
        self.cursor.close()
        self.conn.close()


# data = [2,1, ]
# sql1 = 'select * from sku;'
# result2= DBHandle().query_sql(sql1,one=False)
# print(result2)
# DBHandle().close_db()


